package com.ryder.petmatediarybackend.module.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ryder.petmatediarybackend.common.exception.BusinessException;
import com.ryder.petmatediarybackend.module.shop.dto.CreateProductCollectionDTO;
import com.ryder.petmatediarybackend.module.shop.entity.ShopInfo;
import com.ryder.petmatediarybackend.module.shop.entity.ShopProductCollection;
import com.ryder.petmatediarybackend.module.shop.mapper.ShopProductCollectionMapper;
import com.ryder.petmatediarybackend.module.shop.service.ShopInfoService;
import com.ryder.petmatediarybackend.module.shop.service.ShopProductCollectionService;
import com.ryder.petmatediarybackend.module.shop.vo.ProductCollectionVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述: 店铺商品合集表（仅展示，不含交易）(ShopProductCollection)表服务实现类
 * 
 * @author Ryder
 * @version 1.0
 * @since 1.0
 * 更新日期: 2025-10-31
 */
@Slf4j
@Service("shopProductCollectionService")
@RequiredArgsConstructor
public class ShopProductCollectionServiceImpl extends ServiceImpl<ShopProductCollectionMapper, ShopProductCollection> implements ShopProductCollectionService {

    private final ShopInfoService shopInfoService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ProductCollectionVO createProductCollection(Long userId, CreateProductCollectionDTO dto) {
        log.info("[创建商品合集] userId={}, productName={}", userId, dto.getProductName());

        ShopInfo shopInfo = shopInfoService.getShopByUserId(userId);
        if (shopInfo == null) {
            throw new BusinessException("请先创建店铺");
        }

        // 检查数量限制
        long count = this.lambdaQuery().eq(ShopProductCollection::getShopId, shopInfo.getId()).count();
        if (count >= 50) {
            throw new BusinessException("商品合集最多只能添加50条记录");
        }

        // 验证图片数量
        if (dto.getImages() == null || dto.getImages().isEmpty()) {
            throw new BusinessException("请至少上传一张商品图片");
        }
        if (dto.getImages().size() > 1) {
            throw new BusinessException("每个商品合集最多只能上传1张图片");
        }

        ShopProductCollection productCollection = new ShopProductCollection();
        BeanUtil.copyProperties(dto, productCollection);
        productCollection.setShopId(shopInfo.getId());
        productCollection.setImages(JSONUtil.toJsonStr(dto.getImages()));
        productCollection.setStatus(1); // 默认展示中
        productCollection.setAuditStatus(0); // 待审核

        boolean saved = this.save(productCollection);
        if (!saved) {
            throw new BusinessException("创建商品合集失败");
        }

        log.info("[创建商品合集成功] productCollectionId={}", productCollection.getId());
        return convertToVO(productCollection);
    }

    @Override
    public List<ProductCollectionVO> getMyProductCollections(Long userId) {
        ShopInfo shopInfo = shopInfoService.getShopByUserId(userId);
        if (shopInfo == null) {
            throw new BusinessException("店铺不存在");
        }

        LambdaQueryWrapper<ShopProductCollection> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShopProductCollection::getShopId, shopInfo.getId())
                .orderByDesc(ShopProductCollection::getCreateTime);
        
        List<ShopProductCollection> list = this.list(wrapper);
        return list.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ProductCollectionVO updateProductCollection(Long userId, Long id, CreateProductCollectionDTO dto) {
        log.info("[更新商品合集] userId={}, id={}", userId, id);

        ShopInfo shopInfo = shopInfoService.getShopByUserId(userId);
        if (shopInfo == null) {
            throw new BusinessException("店铺不存在");
        }

        ShopProductCollection productCollection = this.getById(id);
        if (productCollection == null) {
            throw new BusinessException("商品合集不存在");
        }

        if (!productCollection.getShopId().equals(shopInfo.getId())) {
            throw new BusinessException("无权修改该商品合集");
        }

        BeanUtil.copyProperties(dto, productCollection, "id", "shopId");
        if (dto.getImages() != null) {
            productCollection.setImages(JSONUtil.toJsonStr(dto.getImages()));
        }

        boolean updated = this.updateById(productCollection);
        if (!updated) {
            throw new BusinessException("更新商品合集失败");
        }

        log.info("[更新商品合集成功] id={}", id);
        return convertToVO(productCollection);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteProductCollection(Long userId, Long id) {
        log.info("[删除商品合集] userId={}, id={}", userId, id);

        ShopInfo shopInfo = shopInfoService.getShopByUserId(userId);
        if (shopInfo == null) {
            throw new BusinessException("店铺不存在");
        }

        ShopProductCollection productCollection = this.getById(id);
        if (productCollection == null) {
            throw new BusinessException("商品合集不存在");
        }

        if (!productCollection.getShopId().equals(shopInfo.getId())) {
            throw new BusinessException("无权删除该商品合集");
        }

        boolean deleted = this.removeById(id);
        if (!deleted) {
            throw new BusinessException("删除商品合集失败");
        }

        log.info("[删除商品合集成功] id={}", id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatus(Long userId, Long id, Integer status) {
        log.info("[更新商品状态] userId={}, id={}, status={}", userId, id, status);

        ShopInfo shopInfo = shopInfoService.getShopByUserId(userId);
        if (shopInfo == null) {
            throw new BusinessException("店铺不存在");
        }

        ShopProductCollection productCollection = this.getById(id);
        if (productCollection == null) {
            throw new BusinessException("商品合集不存在");
        }

        if (!productCollection.getShopId().equals(shopInfo.getId())) {
            throw new BusinessException("无权修改该商品合集");
        }

        productCollection.setStatus(status);
        boolean updated = this.updateById(productCollection);
        if (!updated) {
            throw new BusinessException("更新商品状态失败");
        }

        log.info("[更新商品状态成功] id={}", id);
    }

    @Override
    public List<ProductCollectionVO> getByShopId(Long shopId) {
        log.info("[查询店铺商品合集] shopId={}", shopId);
        
        LambdaQueryWrapper<ShopProductCollection> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShopProductCollection::getShopId, shopId)
                .eq(ShopProductCollection::getStatus, 1) // 只查询展示中的
                .eq(ShopProductCollection::getAuditStatus, 1) // 只查询审核通过的
                .orderByDesc(ShopProductCollection::getCreateTime);
        
        List<ShopProductCollection> list = this.list(wrapper);
        log.info("[查询店铺商品合集成功] shopId={}, 数量={}", shopId, list.size());
        
        return list.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    private ProductCollectionVO convertToVO(ShopProductCollection productCollection) {
        ProductCollectionVO vo = new ProductCollectionVO();
        BeanUtil.copyProperties(productCollection, vo);

        if (productCollection.getImages() != null) {
            vo.setImages(JSONUtil.toList(productCollection.getImages(), String.class));
        }

        vo.setProductTypeText(getProductTypeText(productCollection.getProductType()));
        vo.setStatusText(getStatusText(productCollection.getStatus()));
        vo.setAuditStatusText(getAuditStatusText(productCollection.getAuditStatus()));

        return vo;
    }

    private String getProductTypeText(Integer productType) {
        if (productType == null) return "未知";
        return switch (productType) {
            case 1 -> "食品";
            case 2 -> "用品";
            case 3 -> "玩具";
            case 4 -> "服务";
            case 5 -> "其他";
            default -> "未知";
        };
    }

    private String getStatusText(Integer status) {
        if (status == null) return "未知";
        return switch (status) {
            case 1 -> "展示中";
            case 2 -> "已下架";
            default -> "未知";
        };
    }

    private String getAuditStatusText(Integer auditStatus) {
        if (auditStatus == null) return "未知";
        return switch (auditStatus) {
            case 0 -> "待审核";
            case 1 -> "审核通过";
            case 2 -> "审核驳回";
            default -> "未知";
        };
    }
}
